import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;


public class ValidCharacterCounter extends DocumentFilter {

	public ValidCharacterCounter(Console inst) {
		console = inst;
	}
	
	/*
	 * String text = d.getText(de.getOffset(), de.getLength());
			
			for (int i = 0; i < text.length(); i++)
				if (Character.isLetterOrDigit(text.charAt(i)))
						charsRemaning--;
	 */

	@Override
	public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
		
		for (int i = 0; i < string.length(); i++)
			if (Character.isLetterOrDigit(string.charAt(i)))
					charsRemaining--;
		
		console.updateCharsRemaining(charsRemaining);
		
		super.insertString(fb, offset, string, attr);
	}
	
	@Override
	public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
		
		for (int i = 0; i < text.length(); i++)
			if (Character.isLetterOrDigit(text.charAt(i)))
					charsRemaining--;
		
		console.updateCharsRemaining(charsRemaining);
		
		super.replace(fb, offset, length, text, attrs);
	}
	
	@Override
	public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
		String text = fb.getDocument().getText(offset, length);
		
		for (int i = 0; i < text.length(); i++)
			if (Character.isLetterOrDigit(text.charAt(i)))
					charsRemaining++;
		
		console.updateCharsRemaining(charsRemaining);
		
		super.remove(fb, offset, length);
	}
	
	private Console console;
	private int charsRemaining = 512;
}
